package com.qianchang.microfinance.view.mine.loan;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.AccountIdBean;
import com.qianchang.microfinance.bean.HSUploadFileBean;
import com.qianchang.microfinance.bean.LoanProductBean;
import com.qianchang.microfinance.bean.LoanProgBean;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.ProjectStatus;
import com.qianchang.microfinance.bean.SubmitLoanBean;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.bean.event.AgreementEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.view.MainActivity;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.mine.RechargeActivity;
import com.qianchang.microfinance.view.mine.WithDrawActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tsign.esign.tsignsdk2.TESeal;
import cn.tsign.esign.tsignsdk2.custom.Custom;
import cn.tsign.esign.tsignsdk2.custom.DialogCustom;
import cn.tsign.esign.tsignsdk2.enums.EnumTipMsgGravity;
import cn.tsign.esign.tsignsdk2.enums.EnumWindow;
import cn.tsign.esign.tsignsdk2.util.extend.Callback;
import cn.tsign.network.enums.EnumHandSignColor;


/**
 * 借款进度 /充值结果等 显示activity
 */
public class LoanProgressActivity extends BaseActivity {

    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.tv_status)
    DTextView tvStatus;
    @BindView(R.id.tv_amount)
    DTextView tvAmount;
    @BindView(R.id.btn_finish)
    DButton btnFinish;
    @BindView(R.id.tv_back)
    DTextView tvback;
    @BindView(R.id.tv_msg)
    DTextView tvMsg;
    @BindView(R.id.ll_msg)
    LinearLayout llMsg;
    @BindView(R.id.tv_protocol)
    TextView tvProtocol;
    private int progressType;//属于什么  借款进度 /充值结果
    private static final int type_Loan = 0;
    private static final int type_Recharge = 1;
    private static final int type_With_draw = 2;
    private static final int type_Loan_list = 3;
    private String status;
    private String applyAmount;
    private boolean dblclick = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loan_progress);
        ButterKnife.bind(this);
        initView();
        initData();
        initAgrend();
        setCustomStyle();       //2018.1.16鸿胜科技新增
        getSignAccountId();

    }

    @Override
    protected void initView() {
        super.initView();
        tvback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MainActivity.class, true);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (bundle != null) {
            //显示借款进度
            setTitleName(getString(R.string.title_loan_proress));
//                submitLoanBean = (SubmitLoanBean) bundle.getSerializable(SubmitLoanBean.class.getName());
            status = bundle.getString(ConstantAppInfo.PROJECT_STATUS);
            applyAmount = bundle.getString(SubmitLoanBean.LOAN_AMOUNT);

            projectId = bundle.getString(ConstantAppInfo.PROJECT_ID);
            projectType = bundle.getInt(ConstantAppInfo.PROJECT_TYPE);

            //显示充值进度
            if (bundle.containsKey(RechargeActivity.class.getName())) {
                progressType = type_Recharge;
                setTitleName(getString(R.string.recharge));
                double intAmount = bundle.getDouble(RechargeActivity.class.getName(), 0);
                refreshRecharge(intAmount);
            } else if (bundle.containsKey(WithDrawActivity.class.getName())) {        //显示提现
                progressType = type_With_draw;
                setTitleName(getString(R.string.withdraw));
                Double intAmount = bundle.getDouble(WithDrawActivity.class.getName(), 0);
                refreshWithDraw(intAmount);
            } else {
                int from = bundle.getInt(ConstantAppInfo.FROM);
                if (from == 1) {
                    progressType = type_Loan_list;
                } else {
                    progressType = type_Loan;
                }
                refreshLoan();
            }
        }

    }


    private void refreshWithDraw(Double intAmount) {
        tvStatus.setTextContent(getString(R.string.Label_WithDraw_success));
        tvAmount.setTextContent("¥" + FormatUtil.numKbPointFormat(intAmount));
        imageView.setBackgroundResource(R.drawable.img_txcg);
        llMsg.setVisibility(View.GONE);
    }

    private void refreshRecharge(Double intAmount) {
        tvStatus.setTextContent(getString(R.string.Label_Recharge_success));
        tvAmount.setTextContent("¥" + FormatUtil.numKbPointFormat(intAmount));
        imageView.setBackgroundResource(R.drawable.img_czcg);
        llMsg.setVisibility(View.GONE);

    }

    private void refreshLoan() {
//        tvStatus.setText(submitLoanBean.getStatusDesc() + "");
//        tvAmount.setText(submitLoanBean.getApplyAmount() + "");
        tvStatus.setTextContent(ProjectStatus.getStatusName(status));
        tvAmount.setTextContent("¥" + FormatUtil.numKbPointFormat(applyAmount));
        switch (status) {
            case ProjectStatus.SHZ:
//                imageView.setBackgroundResource(R.drawable.img_shz);    //注释掉迪蒙原来代码 2018.1.16
                imageView.setBackgroundResource(R.drawable.img_money);            //鸿胜科技新增自己代码 2018.1.16
                tvMsg.setTextContent("借款进度当前为审核中，请耐心等待");
                break;
            case ProjectStatus.DFK:
                imageView.setBackgroundResource(R.drawable.img_fkz);
                tvMsg.setTextContent("放款结果将会以短信告知，请耐心等待");
                break;
        }
        llMsg.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        switch (progressType) {
            case type_Loan:
//                startActivity(MainActivity.class, true);                  //2018.1.16 注释掉迪蒙原来代码

//                startActivity(HSLoanWithdrawActivity.class, true);          //2018.1.16新增鸿胜科技跳转提现页面测试使用
                   if(dblclick == true){
                       checkAgreement();
                       dblclick = false;
                   }else{
                       ToastUtil.getInstant().show(LoanProgressActivity.this, "很抱歉，不能重复点击！");
                   }



                break;
            case type_Recharge:
                setResult(RESULT_OK);
                finish();
                break;
            case type_With_draw:
                setResult(RESULT_OK);
                finish();
                break;
            case type_Loan_list:
                startActivity(MyLoanActivity.class, true);
                break;
        }
    }

    /**
     * 2018.1.16鸿胜科技新增
     */
    private String projectId;
    private int projectType;
    private String accountId;
    private static final String TAG = "ConfirmAgreement";

    // 对SDK里的页面做一些样式设置
    private void setCustomStyle() {
        //对SDK做个性化设置
        Custom custom = new Custom();
        //设置标题的背景颜色
        custom.setTitleBackgroundColor(R.color.black);
        //设置标题的文字颜色
        custom.setTitleTextColor(R.color.red);
        //设置标题文本
        custom.setTitleText(R.string.Label_sure_agreement);
        //设置手绘签名前的提示语
        custom.setTipMsg("请签名");
        //设置提示语对齐方向
        custom.setTipMsgGravity(EnumTipMsgGravity.center);
        //设置手绘的签署提供的颜色,只能是红,黑,蓝
        custom.getHandColor().add(EnumHandSignColor.Blue);
        custom.getHandColor().add(EnumHandSignColor.Black);
        custom.getHandColor().add(EnumHandSignColor.Red);

        //快捷签弹出式对话框的样式
        DialogCustom dialogCustom = new DialogCustom();
        dialogCustom.setCancelResourceId(R.drawable.tsign_quick_sign_dialog_cancel);
        dialogCustom.setFullScreenResourceId(R.drawable.tsign_quick_sign_dialog_full_screen);
        dialogCustom.setClearResourceId(R.drawable.tsign_quick_sign_dialog_clear);
        dialogCustom.setConfirmResourceId(R.drawable.tsign_quick_sign_dialog_confirm);
        custom.setDialogCustom(dialogCustom);

        TESeal.getInstance().setmCustom(custom);
    }


    private void getSignAccountId() {

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        HttpParams params = new HttpParams();
        params.put("userId",usid);

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.ES_CREATEAGREE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    DMLog.e(TAG, "onSuccess: " + response.getObject());
                    accountId = response.getObject();
//                    try {
//                        JSONObject jsonData = new JSONObject(response.getObject());
//                        if (jsonData.has("data")) {
//                            accountId = jsonData.getString("data");
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }

                } else {
                    ToastUtil.getInstant().show(LoanProgressActivity.this, response.getDescription());
                }
            }


            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(LoanProgressActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }



    /**
     * 确认合同
     */
    private void checkAgreement() {
        TESeal.getInstance().quickToSign(LoanProgressActivity.this, accountId, EnumWindow.Dialog, new Callback() {

            @Override
            public void didSignBackImage(String id, String sealImagePath) {
//                uploadFile(sealImagePath);            //2018.1.24注释迪蒙代码

                hsuploadFile(sealImagePath);
            }

            @Override
            public void onError(JSONObject json) {
                dblclick = true;
                ToastUtil.getInstant().show(LoanProgressActivity.this, json.toString());
            }

            @Override
            public void onCancel(JSONObject json) {
                dblclick = true;
                //ToastUtil.getInstant().show(LoanProgressActivity.this, json.toString());
            }
        });
    }

    /**
     * 只有单个文件才支持上传
     *
     * @param imagePath 文件路径
     */
    public void uploadFile(final String imagePath) {
        if (null == imagePath) {
            return;
        }
        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        show();
        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.UPLOAD_FILE, fileParamsMap, "uploadFile", files, new RequestCallBack<ArrayList<UploadFileBean>>() {

            @Override
            public void onSuccess(JsonResult<ArrayList<UploadFileBean>> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ArrayList<UploadFileBean> uploadFileList = response.getObject();
                    if (null != uploadFileList && uploadFileList.size() > 0) {
                       confirm(uploadFileList.get(0).getId());
                    } else {
                        dismiss();
                        ToastUtil.getInstant().show(LoanProgressActivity.this.getApplicationContext(), getString(R.string.upload_failed));
                    }
                } else {
                    dismiss();
                    ToastUtil.getInstant().show(LoanProgressActivity.this.getApplicationContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(LoanProgressActivity.this.getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    public void confirm(String fileId) {

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        HttpParams params = new HttpParams();
        params.put("projectId", projectId);
        params.put("userType", "");
        params.put("method", "confirm");
        params.put("status", "5");
//        params.put("fileId", fileId);
        params.put("amount",applyAmount);
        params.put("userId",usid);


        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/project/" + LoanType.getNameByType(String.valueOf(projectType)) + DMConstant.Config.V + "/confirm.do", params, new RequestCallBack<LoanProgBean>() {
            @Override
            public void onSuccess(JsonResult<LoanProgBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    if (LoanType.JBD.equals(String.valueOf(projectType))) {
//                        Bundle bundle = getBundle();//注释掉迪蒙代码 2018.1.25
//                        bundle.putString(ConstantAppInfo.PROJECT_STATUS, ProjectStatus.DFK);//注释掉迪蒙代码  2018.1.25
//                        startActivity(LoanProgressActivity.class, bundle);    //注释掉迪蒙代码  2018.1.25

                        LoanProgBean loanProgBean = response.getObject();
                        if(loanProgBean != null){
                            String biadid = loanProgBean.getBiaodiId();
                            String userId = loanProgBean.getUserId();
                            Bundle bundle = new Bundle();
                            bundle.putString("userId",userId);
                            bundle.putString("bidId",biadid);

                            startActivity(HSLoanWithdrawActivity.class,bundle);
                            if(biadid.equals("") == false && null != biadid){
                                dblclick = true;
                            }else{
                                dblclick = false;
                            }

                        }else {
                            dblclick = true;
                            ToastUtil.getInstant().show(LoanProgressActivity.this, "申请失败");
                        }
                    } else {
                        dblclick = true;
                        ToastUtil.getInstant().show(LoanProgressActivity.this, "申请失败");
                    }
                    EventBus.getDefault().post(new AgreementEvent(true));
                    finish();
                } else {
                    dblclick = true;
                    ToastUtil.getInstant().show(LoanProgressActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(LoanProgressActivity.this, msg);
                dblclick = true;
            }

            @Override
            public void onConnectFailure(String msg) {
                dblclick = true;
            }
        });
    }


    /**
     * 只有单个文件才支持上传
     *
     * @param imagePath 文件路径
     */
    public void hsuploadFile(final String imagePath) {
        if (null == imagePath) {
            return;
        }

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        fileParamsMap.put("userId",usid);
        fileParamsMap.put("projectId",projectId);

        show();
        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.WFILE_UPLOAD, fileParamsMap, "uploadFile", files, new RequestCallBack<HSUploadFileBean>() {

            @Override
            public void onSuccess(JsonResult<HSUploadFileBean> response) {

                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    HSUploadFileBean uploadFileBean = response.getObject();
                        confirm("");
//                    if (null != uploadFileBean ) {
//                        confirm(uploadFileBean.getId());
//                    } else {
//                        dismiss();
//                        ToastUtil.getInstant().show(LoanProgressActivity.this.getApplicationContext(), getString(R.string.upload_failed));
//                    }
                } else {

                      //confirm("");
                    dblclick = true;
                    dismiss();
                    ToastUtil.getInstant().show(LoanProgressActivity.this, response.getDescription());
                    //ToastUtil.getInstant().show(LoanProgressActivity.this.getApplicationContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {

                dismiss();
               ToastUtil.getInstant().show(LoanProgressActivity.this.getApplicationContext(), msg);
                dblclick = true;
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                dblclick = true;
            }
        });
    }

    private void initAgrend(){

        tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        tvProtocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
        SpanUtils spanUtils = new SpanUtils();
        spanUtils.append(getString(R.string.Label_reading)).setForegroundColor(getResources().getColor(R.color.common_black_color_6)).append("《" + "借款合同" + "》")
        .setClickSpan(new ClickableSpan() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), ConfirmAgreementActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(ConstantAppInfo.PROJECT_ID, projectId);
                bundle.putInt(ConstantAppInfo.PROJECT_TYPE, projectType);
                bundle.putString(SubmitLoanBean.LOAN_AMOUNT, applyAmount);
                bundle.putInt(ConstantAppInfo.FROM, 1);
                intent.putExtras(bundle);
                startActivityForResult(intent,100);
//                LoanProgressActivity.this.finish();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.common_blue_color_light));            //  R.color.common_orange_color_light
                ds.setUnderlineText(false);
            }
        });
        tvProtocol.setText(spanUtils.create());
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 && resultCode == -1){             //如果从这里跳转至合同页面点击合同确认提交借款返回这里的时候结束页面
            LoanProgressActivity.this.finish();
        }
    }
}
